﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeCamp12.Domain;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using log4net;

namespace CodeCamp12.Domain
{
    public class FileDataManagement
    {
        private ConnectionStringProvider connString = new ConnectionStringProvider();
        private ILog log = LogManager.GetLogger("CodeCamp12.DAL");

        /// <summary>
        /// Inserts new file in the database
        /// </summary>
        /// <param name="file"></param>
        public void InsertFile(Domain.File file)
        {
            var conn = connString.GetConnection();
            var comm = new SqlCommand("InsertFile", conn) {CommandType = System.Data.CommandType.StoredProcedure};

            comm.Parameters.AddWithValue("@FileName", file.FileName);
            comm.Parameters.AddWithValue("@FileType", file.FileType);
            comm.Parameters.AddWithValue("@SpeakerID", file.SpeakerID);

            var documentBinary = new byte[file.FileData.Length];
            file.FileData.Read(documentBinary, 0, Convert.ToInt32(file.FileData.Length));
            
            comm.Parameters.AddWithValue("@FileData", documentBinary);
            try
            {
                conn.Open();
                comm.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                log.Error(ex);
                throw;
            }
            finally
            {
                conn.Close();
            }
        }

        /// <summary>
        /// Updates file in the database
        /// </summary>
        /// <param name="file"></param>
        public void UpdateFileForSpeaker(Domain.File file)
        {
            var conn = connString.GetConnection();
            SqlCommand comm;
            if(file.FileType.Equals(".jpg") || file.FileType.Equals(".png"))
                comm = new SqlCommand("UpdateImage", conn);
            else
                comm = new SqlCommand("UpdateDocument", conn);
            comm.CommandType = System.Data.CommandType.StoredProcedure;
            comm.Parameters.AddWithValue("@FileName", file.FileName);
            comm.Parameters.AddWithValue("@FileType", file.FileType);

            var documentBinary = new byte[file.FileData.Length];
            file.FileData.Read(documentBinary, 0, Convert.ToInt32(file.FileData.Length));
            
            comm.Parameters.AddWithValue("@FileData", documentBinary);
            comm.Parameters.AddWithValue("@SpeakerID", file.SpeakerID);

            try
            {
                conn.Open();
                comm.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                log.Error(ex);
                throw;
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
